package dragon.core.runtime;


import org.junit.Test;

import dragon.core.db.ColumnMeta;
import dragon.core.db.DML;
import dragon.core.db.TableMeta;
import dragon.core.exception.ExceptionHandler;
import dragon.core.io.FileHandler;
import dragon.core.util.StringUtils;


public class GeneratorTableXML {
	
	private static final String FILE_PATH = "D:/";//文件输出路径
	
	private static final String SCHEMANAME = "app";//表模式
	
	private static final String TABLE_NAME = "article";//表名
	
	
	@Test
	public  void test(){
		String[] pks = new String[] { "id" };
		try {
			String  output = generate("app","article",pks);
			
			FileHandler.createPlainTextFile(FILE_PATH+SCHEMANAME+"."+TABLE_NAME+".xml", output, null);
		
			
		} catch (ExceptionHandler e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据指定的数据表生成XML文件内容
	 * 
	 * @param schemaname
	 * @param tableName
	 * @param pks
	 * @throws ExceptionHandler
	 */
	public String generate(String schemaname, String tableName, String... pks) throws ExceptionHandler {
		StringBuffer sb_xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Table xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n\t<orderNum>1</orderNum>\n");
		
		sb_xml.append("\t<Code>").append(schemaname).append(".").append(tableName).append("</Code>\n");
		sb_xml.append("\t<Name>").append(tableName).append("</Name>\n");
		
		if (StringUtils.isEmpty(tableName)) {
			return null;
		}
		// 读取数据表字段元数据
		TableMeta table = DML.getTableMeta(schemaname, tableName, pks);
		if (table == null) {
			throw new ExceptionHandler("数据表或视图：" + tableName + " 不存在！");
		}
		sb_xml.append("\t<Fields>\n");
		int i = 1;
		for(ColumnMeta cm:table.getColumns()){
			sb_xml.append("\t\t<Field>\n");
			sb_xml.append("\t\t\t<orderNum>").append(i).append("</orderNum>\n");
			
			sb_xml.append("\t\t\t<Name>").append(cm.getColumnLabel()).append("</Name>\n");
			sb_xml.append("\t\t\t<Code>").append(cm.getColumnName().toLowerCase()).append("</Code>\n");
			sb_xml.append("\t\t\t<Type>").append(cm.getColumnTypeName().toUpperCase()).append("</Type>\n");
			sb_xml.append("\t\t\t<length>").append(cm.getColumnDisplaySize()).append("</length>\n");
			
			sb_xml.append("\t\t</Field>\n");
			i++;
		}
		sb_xml.append("\t</Fields>\n");
		sb_xml.append("</Table>\n");
		return sb_xml.toString().replaceAll("BPCHAR", "CHAR");
	}
	
}
